package com.youzan.cloud.component.biz.member.service.impl;
import com.alibaba.fastjson.JSON;
import com.youzan.cloud.component.base.util.core.ObjectUtil;
import com.youzan.cloud.component.biz.member.common.util.LogRecordUtil;
import com.youzan.cloud.component.biz.member.common.util.OutResultUtil;
import com.youzan.cloud.component.biz.member.config.MemberLinkerConfiguration;
import com.youzan.cloud.component.biz.member.dal.dataobject.MemberInformation;
import com.youzan.cloud.component.biz.member.dal.dataobject.MemberRelationship;
import com.youzan.cloud.component.biz.member.dal.mapper.MemberInformationMapper;
import com.youzan.cloud.component.biz.member.dal.mapper.MemberRelationshipMapper;
import com.youzan.cloud.component.biz.member.dto.BaseResult;
import com.youzan.cloud.component.biz.member.dto.LogDTO;
import com.youzan.cloud.component.biz.member.dto.MemberBaseDto;
import com.youzan.cloud.component.biz.member.dto.linker.out.MemberCreateLinkerResult;
import com.youzan.cloud.component.biz.member.dto.linker.out.MemberLinkerBaseResult;
import com.youzan.cloud.component.biz.member.dto.linker.out.MemberQueryResult;
import com.youzan.cloud.component.biz.member.youzanopen.api.YzMemberApiService;
import com.youzan.cloud.connect.service.common.domain.BizServiceInfo;
import com.youzan.cloud.connect.service.sdk.ConnectServiceResponse;
import com.youzan.cloud.connect.service.sdk.exception.ConnectServiceCallException;
import com.youzan.cloud.open.sdk.gen.v1_0_0.model.YouzanUsersInfoQueryResult;
import com.youzan.cloud.open.sdk.gen.v1_0_1.model.YouzanScrmCustomerDetailGetResult;
import com.youzan.cloud.open.sdk.gen.v3_0_0.model.YouzanScrmCustomerGetResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import java.util.Date;

@Service
@Slf4j
public class MemberCreateService extends AbstractService {


    @Autowired
    private MemberRelationshipMapper memberRelationshipMapper;

    @Autowired
    private MemberLinkerConfiguration memberLinkerConfiguration;

    @Autowired
    private LogRecordUtil logRecordUtil;

    @Autowired
    private YzMemberApiService yzMemberApiService;

    @Autowired
    private MemberInformationMapper memberInformationMapper;

    @Override
    public LogDTO buildLog(Object inputParam) {

        return null;
    }

    @Override
    public BaseResult handleException(Exception e) {
        // TODO 捕获异常
        return OutResultUtil.fail("组件异常!","500",e);
    }

    @Override
    public BaseResult doBiz(MemberBaseDto memberBaseDto) {
        String yzOpenId = memberBaseDto.getYzOpenId();
        MemberRelationship memberRelationship = memberRelationshipMapper.selectByYzOpenId(yzOpenId);
        //用户已存在 直接返回
        if(ObjectUtil.isNotNull(memberRelationship)){
           return OutResultUtil.success(memberRelationship);
        }
        Long logRecordId = null;
        //查询连接器
        BizServiceInfo memberQueryLinker = memberLinkerConfiguration.getMemberQueryLinker();
        if(ObjectUtil.isEmpty(memberQueryLinker)){
            return OutResultUtil.fail("构建会员查询连接器linker为空","500",null);
        }
        BizServiceInfo memberCreateLinkerInfo = memberLinkerConfiguration.getMemberCreateLinker();
        if(ObjectUtil.isEmpty(memberCreateLinkerInfo)){
           return OutResultUtil.fail("构建会员创建连接器linker为空","500",null);
        }
            ConnectServiceResponse<MemberLinkerBaseResult> queryMemberResult = null;
            ConnectServiceResponse<MemberLinkerBaseResult> createMemberResult = null;
          try {
              queryMemberResult = connectServiceCaller.callConnectService(memberQueryLinker.getConnectServiceName(),memberQueryLinker.getTargetSystem(),memberQueryLinker.getTargetSystemVersion(),memberBaseDto.getMemberQueryDto());
          }catch (ConnectServiceCallException e){
              log.error("调用会员查询连接器失败" + e.getMessage());
              return OutResultUtil.fail(queryMemberResult.getErrMsg(),queryMemberResult.getErrorCode().toString(),queryMemberResult);
          }
          if(ObjectUtil.isEmpty(queryMemberResult)){
              return OutResultUtil.fail("调用会员查询连接器失败","500",null);
          }
        //用户信息存在则证明三方已经是会员 直接同步db
          if(queryMemberResult.isSuccess()){
              MemberQueryResult memberQueryResult = (MemberQueryResult)queryMemberResult.getResponseDTO();
              saveMemberRelationship(memberBaseDto,memberQueryResult.getThirdAccount(),memberQueryResult.getThirdAccountType());
              BaseResult baseResult = saveMemberInformation(memberBaseDto, memberQueryResult);
              if(baseResult.isSuccess()){
                  return OutResultUtil.success(baseResult);
              }
          }else{
              //新会员 同步创建
              try {
                  createMemberResult = connectServiceCaller.callConnectService(memberCreateLinkerInfo.getConnectServiceName(),memberCreateLinkerInfo.getTargetSystem(),memberCreateLinkerInfo.getTargetSystemVersion(),memberBaseDto.getMemberCreateDto());
                  logRecordId  = logRecordUtil.saveLogRecord(memberCreateLinkerInfo.getConnectServiceName(), memberCreateLinkerInfo.getConnectServiceName(), JSON.toJSONString(memberBaseDto.getMemberCreateDto()), createMemberResult.getResponseDTO().toString());
              } catch (ConnectServiceCallException e) {
                  log.error("调用三方注册会员接口失败" + e.getMessage());
                  return OutResultUtil.fail(createMemberResult.getErrMsg(),createMemberResult.getErrorCode().toString(),createMemberResult);
              }
              if(createMemberResult.isSuccess()){
                  MemberCreateLinkerResult createLinkerResult = (MemberCreateLinkerResult) createMemberResult.getResponseDTO();
                  //创建成功 调查询连接器 同步信息
                  ConnectServiceResponse<MemberLinkerBaseResult> result = null;
                  try {
                     result = connectServiceCaller.callConnectService(memberQueryLinker.getConnectServiceName(),memberQueryLinker.getTargetSystem(),memberQueryLinker.getTargetSystemVersion(),memberBaseDto.getMemberQueryDto());
                  }catch (ConnectServiceCallException e){
                      log.error("调用三方查询会员接口失败" + e.getMessage());
                      return OutResultUtil.fail(result.getErrMsg(),result.getErrorCode().toString(),result);
                  }
                  MemberQueryResult memberQueryResult = (MemberQueryResult)queryMemberResult.getResponseDTO();
                  saveMemberRelationship(memberBaseDto,createLinkerResult.getThirdAccount(),createLinkerResult.getThirdAccountType());
                  BaseResult baseResult = saveMemberInformation(memberBaseDto, memberQueryResult);
                  if(baseResult.isSuccess()){
                      return OutResultUtil.success(baseResult);
                  }
              }
          }
        return OutResultUtil.fail("调用会员查询连接器异常",createMemberResult.getErrorCode().toString(),null);
    }


    public void  saveMemberRelationship(MemberBaseDto memberBaseDto,String thirdAccount,String thirdAccountType){
        MemberRelationship memberRelation = new MemberRelationship();
        memberRelation.setYzOpenid(memberBaseDto.getYzOpenId());
        memberRelation.setThirdAccount(thirdAccount==null?null:thirdAccount);
        memberRelation.setThirdAccountType(thirdAccountType==null?"1":thirdAccountType);
        memberRelation.setCreateTime(new Date());
        memberRelation.setKdtid(memberBaseDto.getKdtId()==null?null:Long.valueOf(memberBaseDto.getKdtId()));
        memberRelation.setMobile(memberBaseDto.getMobile());
        memberRelationshipMapper.insertIgnoreNull(memberRelation);
    }


    public BaseResult saveMemberInformation(MemberBaseDto memberBaseDto, MemberQueryResult memberQueryResult){
        //查询有赞侧信息
        YouzanUsersInfoQueryResult.YouzanUsersInfoQueryResultData userInfo = yzMemberApiService.queryResultData(memberBaseDto.getYzOpenId(),memberBaseDto.getKdtId());
        YouzanScrmCustomerDetailGetResult.YouzanScrmCustomerDetailGetResultData youzanScrmCustomerDetailGetResultData = yzMemberApiService.getYouzanScrmCustomerDetailGetResultData(memberBaseDto.getKdtId(), memberBaseDto.getYzOpenId());
       // YouzanScrmCustomerGetResult.YouzanScrmCustomerGetResultData youzanScrmCustomerGetResultData = yzMemberApiService.getYouzanScrmCustomerGetResultData(memberBaseDto.getKdtId(), memberBaseDto.getMobile());
        if(ObjectUtils.isEmpty(userInfo)){
            OutResultUtil.fail("调用有赞用户查询API信息为空","500",null);
        }
        MemberInformation information  = memberInformationMapper.selectByYzOpenId(memberBaseDto.getYzOpenId());
        if(ObjectUtil.isNotNull(information)){
            //信息已存在做修改
            yzMemberApiService.setPropertiesInformation(information,memberQueryResult,memberBaseDto,userInfo,youzanScrmCustomerDetailGetResultData);
            memberInformationMapper.updateIgnoreNull(information);
        }else{
            //记录会员基本信息
            MemberInformation memberInformation = new MemberInformation();
            yzMemberApiService.setPropertiesInformation(memberInformation,memberQueryResult,memberBaseDto,userInfo,youzanScrmCustomerDetailGetResultData);
            memberInformationMapper.insertIgnoreNull(memberInformation);
        }
        //查询等级连接器
        BaseResult memberLevel = yzMemberApiService.getMemberLevel(memberBaseDto.getYzOpenId(), memberBaseDto.getKdtId(), memberBaseDto);
        return memberLevel;
    }
}
